package com.nononsenseapps.feeder.sync.local.source.url

import com.nononsenseapps.feeder.parser.FeedParser
import com.nononsenseapps.feeder.parser.safeBody
import com.nononsenseapps.feeder.sync.local.ResponseFailure
import com.nononsenseapps.feeder.sync.local.fetchFeed
import com.nononsenseapps.jsonfeed.Feed
import okhttp3.Response

object URLSource {
     suspend fun fetchFeedForUrl(feedSql: com.nononsenseapps.feeder.db.entity.Feed,
                                        feedParser: FeedParser,
                                        forceNetwork: Boolean = false
    ): Feed?{
        val response: Response = fetchFeed(feedParser, feedSql, forceNetwork = forceNetwork)
        var responseHash=0
        val parserFeed: Feed?= response.use {
            val responseBody = it.safeBody()
            responseBody?.let { body ->
                if(!response.isSuccessful)
                    throw ResponseFailure("${response.code} when fetching ${feedSql.displayTitle}: ${feedSql.url}")
                responseHash = body.contentHashCode()
                when(feedSql.responseHash != responseHash ) {
                    true -> feedParser.parseObjectResponse(it, body)
                    else -> null
                }
            }
        }
        parserFeed?.let {
            it.responseHash=responseHash
        }
        return parserFeed
    }
}